/**
 * Router
 */

'use strict';

module.exports = function(app) {
    const qs = require('qs');
    const fs = require('fs');
    const parse = require('co-body');
    let koaRequest = require('koa-request');
    let HttpResponse = require('../common/httpResponse')
    const httpMethod = require('../common/httpMethod').httpRequest
    const SECRET_KEY = 'be34a56584a8dc499ae4845b89d77700';

    app.post('/user/login.action', httpMethod({
        type: 'POST'
    }))
    app.get('/ecs/shop/index/ad.action', httpMethod())
    app.get('/ecs/goods/list.action', httpMethod())
    app.get('/ecs/goods/detail.action', httpMethod())
    app.get('/ecs/goods/list.action', httpMethod())
    app.get('/ecs/goods/category.action', httpMethod())
    app.get('/ecs/brand/list.action', httpMethod())
    app.get('/region/list.action', httpMethod())
    app.get('/region/getRegionById.action', httpMethod())
    app.post('/ecs/address/add.action', httpMethod({
        type: 'POST'
    }))
    app.post('/ecs/address/modify.action', httpMethod({
        type: 'POST'
    }))
    app.get('/ecs/address/list.action', httpMethod())
    app.get('/ecs/address/remove.action', httpMethod())
    app.get('/ecs/shipping/list.action', httpMethod())
    app.get('/ecs/cart/list.action', httpMethod())
    app.post('/ecs/cart/remove.action', httpMethod({
        type: 'POST'
    }))
    app.post('/ecs/cart/modify.action', httpMethod({
        type: 'POST'
    }))

    app.post('/ecs/order/add.action', httpMethod({
        type: 'POST'
    }))
    app.get('/ecs/order/list.action', httpMethod())
    app.get('/ecs/order/detail.action', httpMethod())

    app.post('/ecs/cart/add.action', httpMethod({
        type: 'POST'
    }))
    app.post('/ecs/address/remove.action', httpMethod({
        type: 'POST'
    }))

    app.get('/ecs/brand/detail.action', httpMethod())

    app.post('/ecs/pay/dopay.action', httpMethod({
        type: 'POST'
    }))
    app.get('/ecs/user/myinvite.action', httpMethod())
    app.get('/ecs/order/count.action', httpMethod())
    app.get('/ecs/pay/call/back.action', httpMethod())

    app.post('/ecs/pay/weixin.action', function *(next) {

        var md5 = require('md5');
        let weixinConfig = require('../config/weixin');
        var randomstring = require("randomstring");
        var request = require('request');
        var parseString = require('xml2js').parseString;

        let postData = yield parse(this, { limit: '500kb' }) || null

        var RANDOM_NUM = randomstring.generate({
          length: 16,
          charset: 'alphanumeric'
        });

        let data = Object.assign({}, postData, weixinConfig, {
            nonce_str: RANDOM_NUM,
            spbill_create_ip: getClientIp(this.req)
        })

        var sign = getSign(data);
        data.sign = sign

        var  postXMLData = '<xml>';
            postXMLData += "<appid>"+data.appid+"</appid>";
            postXMLData += "<body>"+data.body+"</body>";
            postXMLData += "<mch_id>"+data.mch_id+"</mch_id>";
            postXMLData += "<nonce_str>"+data.nonce_str+"</nonce_str>";
            postXMLData += "<notify_url>"+data.notify_url+"</notify_url>";
            postXMLData += "<openid>"+data.openid+"</openid>";
            postXMLData += "<out_trade_no>"+data.out_trade_no+"</out_trade_no>";
            postXMLData += "<spbill_create_ip>"+data.spbill_create_ip+"</spbill_create_ip>";
            postXMLData += "<total_fee>"+data.total_fee+"</total_fee>";
            postXMLData += "<sign>"+data.sign+"</sign>";
            postXMLData += "<trade_type>"+data.trade_type+"</trade_type>";
            postXMLData += "</xml>";


        var PFX = process.cwd() + '/server/cert/apiclient_cert.p12';
        function sendRedPack(callback) {
            request({
              url: 'https://api.mch.weixin.qq.com/pay/unifiedorder',
              method: 'POST',
              body: postXMLData
              // agentOptions: {
              //       pfx: fs.readFileSync(PFX),
              //       passphrase: '1235009002'
              // }
            }, function(err, response, body){

                parseString(body, function(err, result) {
                    
                    var result = {
                        code: 200,
                        data: result && result.xml,
                        message: 'success'
                    }
                    callback(null, result)
                })
                
            });
        }
        this.body = yield sendRedPack;

        // 获取签名
        function getSign(obj) {
            // console.log('元素obj:')
            // console.log(obj)
            var parmsString = qs.stringify(obj)
            var stringAArr = parmsString.split('&');
            var stringA = stringAArr.sort().join('&');
            // console.log('第一步:' + stringA)

            // 以上是按ASCII排序

            var stringSignTemp = stringA + '&key=' + SECRET_KEY;
            // console.log('第二步：'+stringSignTemp)

            stringSignTemp = (stringSignTemp)
            var sign = md5(stringSignTemp).toUpperCase();

            // console.log('第四步：'+sign)
            return sign;
        }
    })

    app.post('/ecs/pay/alipay.action', function *(next) {
        let alipayConfig = require('../config/alipay');
        let postData = yield parse(this, { limit: '500kb' }) || null
        // 加密
        let data = Object.assign({}, postData, alipayConfig)
        let sign = getMySign(data)
        data.sign = sign
        data.sign_type = 'MD5';
        let url = `https://mapi.alipay.com/gateway.do?${qs.stringify(data)}`
        this.body = {
            code: 200,
            url
        }

        function getMySign(params, key) {
            let sArr = []
            if(!params) {
                return null
            }
            for(let key in params) {
                if((!params[key]) || key == 'sign' || key == 'sign_type') {
                    console.log('null: ' + key)
                    continue;
                }
                sArr.push([key, params[key]]);
            }
            sArr.sort()

            // 生成签名
            var prestr = '';
            for(let i = 0; i < sArr.length; i++) {
                var obj = sArr[i]
                if(i == sArr.length - 1) {
                    prestr = prestr + obj[0] + '=' + obj[1];
                } else {
                    prestr = prestr + obj[0] + '=' + obj[1] + '&';
                }
            }

            prestr = prestr + 'kma354shmjjkjjkk9qnobfz3qa28v0u2'

            var crypto = require('crypto');
            return crypto.createHash('md5').update(prestr, 'UTF-8').digest("hex");
        }
    })

    app.get('/getAccess/:appid/:code', function *(next) {
        let ACCESS_TOKEN = 'https://api.weixin.qq.com/sns/oauth2/access_token';
        var appid = this.params.appid;
        var code = this.params.code;
        var url = ACCESS_TOKEN + '?appid='+appid+'&secret='+SECRET_KEY+'&code='+code+'&grant_type=authorization_code'
        var config = getCommonConfig(url);
        var response = yield koaRequest(config);
        var body = JSON.parse(response.body)
        HttpResponse(body, this);
        yield next;
    })

    function getClientIp(req) {
        var ip = req.headers['x-forwarded-for'] ||
             req.connection.remoteAddress ||
             req.socket.remoteAddress ||
             req.connection.socket.remoteAddress;

        return ip.replace('::ffff:', '');
    }
    function getCommonConfig (url, cookie, data, method) {
        return {
            body: data && JSON.stringify(data),
            method: method || "GET",
            uri: url,
            headers: {
                "Content-Type": 'application/json',
                "Content-Length": Buffer.byteLength(JSON.stringify(data) || '', 'utf8'),
                "Cookie": cookie || ''
            }
        };
    }


}

